package com.cuckoo.cuckoo_app2.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.widget.ImageView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.EnumMap;
import java.util.Map;

/**
 * 二维码工具
 *
 * @author : jerome
 */
public class QRCodeUtil {

    /**
     * 用于创建一个二维码
     *
     * @param codeContent
     * @param logoBitmap
     * @param codeView
     * @param qrCodeSize
     * @param logoSizePercent
     */
    public static void createQRCode(String codeContent, Bitmap logoBitmap, ImageView codeView, int qrCodeSize, int logoSizePercent) {
        // 配置二维码参数
        Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);

        try {
            // 生成二维码位图
            BitMatrix bitMatrix = new MultiFormatWriter().encode(codeContent, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            int[] pixels = new int[width * height];

            // 将二维码位图转换为像素数组
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = Color.BLACK; // 实际开发中可能需要使用更合适的颜色
                    } else {
                        pixels[y * width + x] = Color.WHITE; // 实际开发中可能需要使用更合适的颜色
                    }
                }
            }

            // 创建Bitmap
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

            // 计算logo的大小
            int logoWidth = (int) (qrCodeSize * (logoSizePercent / 100.0f));
            Bitmap scaledLogo = Bitmap.createScaledBitmap(logoBitmap, logoWidth, logoWidth, true);

            // 在二维码中心添加logo
            Canvas canvas = new Canvas(bitmap);
            int logoLeft = (bitmap.getWidth() - scaledLogo.getWidth()) / 2;
            int logoTop = (bitmap.getHeight() - scaledLogo.getHeight()) / 2;
            canvas.drawBitmap(scaledLogo, logoLeft, logoTop, null);

            // 更新ImageView显示二维码
            codeView.setImageBitmap(bitmap);

        } catch (WriterException e) {
            e.printStackTrace();
            // 处理二维码生成失败的情况
        }
    }
}
